<?php
class DiyAction extends Action {
	private static $html = array ();
	private $layout = array ();
	public function _initialize() {
		$html = <<<EOT
<div class="diy_layout_box">
    <div class="div_tit_sort_box">
        <div class="diy_tit_sort">
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <br/>
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
        </div>
        <div class="diy_tit_sort">
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <br/>
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
        </div>
        <div class="diy_tit_sort">
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <br/>
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
        </div>
        <div class="diy_tit_sort">
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <br/>
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
        </div>
        <div class="diy_tit_sort">
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <br/>
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
        </div>
        <div class="diy_tit_sort no">
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <br/>
            <a href="#"><strong>链接</strong></a>
            <a href="#">链接</a>
            <a href="#">链接</a>
            <a href="#">链接</a>
        </div>
        <div class="C">
        </div>
    </div>
</div>
EOT;
		$navigation ['html'] = $html;
		$navigation ['title'] = '导航模板';
		self::$html ['navigation'] = $navigation;
	}
	public function index() {
		$page = $_GET ['page'];
		$channel = $_GET ['channel'];
		$databaseData = D ( 'Page' )->getPageInfo ( $page, $channel );
		$reuslt = $this->checkRole ( $databaseData ['manager'], $databaseData );
		$parseTag = service ( 'ParseTag' );
		$this->setTitle ( $databaseData ['title'] . " - " . $databaseData ['pageName'] );
		$this->assign ( 'tempData', $databaseData ['layoutData'] );
		$this->assign ( 'layoutData', unserialize ( $databaseData ['widgetData'] ) );
		$pageData = $parseTag->parseId ( $databaseData ['layoutData'] );
		$this->assign ( 'data', $pageData );
		$this->assign ( 'page', $page );
		$this->assign ( 'channel', $channel );
		$this->display ( $databaseData ['html'] );
	}
	
	public function getPopUp() {
		//获取分类
		$this->assign ( "gid", $_GET ['gid'] );
		switch ($_GET ['tagName']) {
			case "w:blog" :
				$group = D ( 'Group', 'group' )->getActive ();
				$cate = D ( 'BlogCategory', 'blog' )->getCategory ( true );
				$this->assign ( 'cate', $cate );
				$this->assign ( 'group', $group );
				break;
			case "w:GroupBlog" :
				if ($_GET ['gid'] != "false") {
					$this->assign ( "cateList", $this->getBlogCateList ( $_GET ['gid'] ) );
				} else {
					$this->assign ( "cateList", "false");
				}
				break;
			case "w:GroupWiki" :
				if ($_GET ['gid'] != "false") {
					$this->assign ( "cateList", $this->getWikiCateList ( $_GET ['gid'] ) );
				} else {
					$this->assign ( "cateList", "false");
				}
				break;
			case "w:GroupForum" :
				if ($_GET ['gid'] != "false") {
					$this->assign ( "cateList", $this->getForumCateList ( $_GET ['gid'] ) );
				} else {
					$this->assign ( "cateList", "false");
				}
				break;
			case "w:GroupFile" :
				if ($_GET ['gid'] != "false") {
					$this->assign ( "cateList", $this->getFileCateList ( $_GET ['gid'] ) );
				} else {
					$this->assign ( "cateList", "false");
				}
				break;
			case "w:ask" :
				$dao = model ( 'Xcate' );
				$cate = $dao->getTree ( 'ask' );
				$this->assign ( 'cate', $cate );
				break;
			case "w:wiki" :
				$cate = $this->getTree ();
				$this->assign ( 'cate', $cate );
				break;
			case "w:group" :
				$group = M ( 'GroupXCategory' )->field ( 'id,name' )->findAll ();
				$this->assign ( 'cate', $group );
				break;
			case "w:user" :
				$group = M ( 'UserGroup' )->field ( 'distinct(gid),gname' )->findAll ();
				$this->assign ( 'cate', $group );
				break;
			case "w:cmsdoc" :
				$channel = M ()->query ( 'select id as a, title as t from ts_portal_channel where status = 1' );
				$cate = M ()->query ( 'select id as a, channelId, name as t from ts_portal_page where pageType = \'list\'' );
				$groupChannel = group ( $cate, 'channelId', 'a,t' );
				//dump($groupChannel);
				foreach ( $channel as &$value ) {
					if (isset ( $groupChannel [$value ['a']] )) {
						$value ['d'] = $groupChannel [$value ['a']];
					}
				}
				$this->assign ( 'channel', $channel );
				//$this->asign('cate',$cate);
				break;
			
			case "w:bbs" :
				$dao = model ( 'Xcate' );
				$board = $dao->getTree ( 'bbs' );
				$cate = D ( 'Core', 'bbs' )->getCateInBoard ();
				$this->assign ( 'cate', $cate );
				$this->assign ( 'board', $board );
				break;
			case "w:custom" :
				foreach ( self::$html as $key => $value ) {
					$var ['style'] [$key] = $value ['title'];
					$var ['htmlTpl'] [$key] = $value ['html'];
				}
				$this->assign ( $var );
				break;
		}
		
		$parseTag = service ( 'ParseTag' );
		if (isset ( $_GET ['sign'] )) {
			$data = $parseTag->getTagInfo ( $_GET ['sign'] );
			$attr = $data ['attr'];
			if (! empty ( $data ['content'] )) {
				$this->assign ( 'html', $data ['content'] );
			}
			list ( $o, $t ) = explode ( " ", $attr ['order'] );
			
			$attr ['order'] = $o;
			$attr ['order_t'] = $t;
			$attr ['content'] = str_replace ( '[@]', '&', $attr ['content'] );
			$attr ['head_link'] = json_encode ( $attr ['head_link'] );
			$this->assign ( 'attr', $attr );
		}
		switch ($_GET ['tagName']) {
			case "w:GroupBlog" :
				if ($attr ['group'] != "") {
					$this->assign ( "cateList", $this->getBlogCateList ( $attr ['group'] ) );
				}
				$this->assign ( "firstCate", json_encode ( explode ( ",", $attr ['cate'] ) ) );
				break;
			case "w:GroupWiki" :
				if ($attr ['group'] != "") {
					$this->assign ( "cateList", $this->getWikiCateList ( $attr ['group'] ) );
				}
				$this->assign ( "firstCate", json_encode ( explode ( ",", $attr ['cate'] ) ) );
				break;
			case "w:GroupForum" :
				if ($attr ['group'] != "") {
					$this->assign ( "cateList", $this->getForumCateList ( $attr ['group'] ) );
				}
				$this->assign ( "firstCate", json_encode ( explode ( ",", $attr ['cate'] ) ) );
				break;
			case "w:GroupFile" :
				if ($attr ['group'] != "") {
					$this->assign ( "cateList", $this->getFileCateList ( $attr ['group'] ) );
				}
				$this->assign ( "firstCate", json_encode ( explode ( ",", $attr ['cate'] ) ) );
				break;
		}
		//获取Tag名
		$popup = str_replace ( ':', "/", $_GET ['tagName'] );
		
		$path = SITE_PATH . '/addons/plugins/Tags/' . $popup . '/popUp.html';
		$this->assign ( 'id', $_GET ['id'] );
		$this->assign ( 'index', $_GET ['index'] );
		$this->assign ( 'parentId', $_GET ['parentId'] );
		$this->assign ( 'layout', $_GET ['needClass'] );
		$this->assign ( 'tagName', $_GET ['tagName'] );
		$this->display ( $path );
	}
	
	public function preview() {
		$parseTag = service ( 'ParseTag' );
		$databaseData = D ( 'Page' )->getPageInfo ( $_GET ['page'], $_GET ['channel'] );
		$layout = Session::get ( 'layout_' . $_GET ['page'] );
		//$page = D('Page')->where("name='".$_GET['page']."'")->getField('pageTemp');
		$content = $this->getLayout ( $layout, $page, $_GET ['toChange'] );
		$content = $parseTag->parseId ( $content );
		$this->assign ( 'data', $content );
		$this->display ( $databaseData ['html'] );
	}
	
	public function setSession() {
		echo Session::set ( $_POST ['name'], $_POST ['layout'] );
	}
	
	public function saveModel() {
		$parseTag = service ( 'ParseTag' );
		$widgetTags = $this->_getTagWidget ( $_POST );
		
		if (is_array ( $widgetTags )) {
			$result ['html'] = $parseTag->parse ( $widgetTags [0], true );
			$result ['widget'] = $widgetTags [1];
		
		} else {
			$result ['html'] = $parseTag->parse ( $widgetTags, true );
			$result ['widget'] = $widgetTags;
		}
		$result ['sign'] = $parseTag->getSign ( $_POST ['tagName'] );
		echo json_encode ( $result );
	}
	public function previewModel() {
		$parseTag = service ( 'ParseTag' );
		$widgetTags = $this->_getTagWidget ( $_POST );
		if (is_array ( $widgetTags )) {
			$result ['html'] = $parseTag->parse ( $widgetTags [0], true );
			$result ['widget'] = $widgetTags [1];
		
		} else {
			$result ['html'] = $parseTag->parse ( $widgetTags, true );
			$result ['widget'] = $widgetTags;
		}
		
		echo json_encode ( $result );
	}
	
	function saveLayout() {
		$page = t ( $_POST ['page'] );
		$channel = t ( $_POST ['channel'] );
		$toChange = t ( $_POST ['toChange'] );
		$databaseData = D ( 'Page' )->getPageInfo ( $page, $channel );
		$check = $this->checkRole ( $databaseData ['manager'], $databaseData );
		if (! $check ['admin']) {
			echo U ( 'portal/index/index/', 'page=' . $page . "&channel=" . $channel );
			exit ();
		}
		$content = $this->getLayout ( $_POST ['layout'], $page, $toChange );
		//对数据进行处理
		if (empty ( $content )) {
			$content = null;
		}
		
		if (is_file ( HTML_PATH . $channel . '_' . $page . '.shtml' )) {
			unlink ( HTML_PATH . $channel . '_' . $page . '.shtml' );
		}
		
		$result = D ( 'Page' )->saveData ( $channel, $page, $content, $this->layout, $this->mid, $databaseData ['id'] );
		//D('Log','admin')->addLog($this->mid, array('channel'=>$channel, 'page'=>$page), 'portal_page');
		//dump(D('Page')->getLastSql());
		echo U ( 'portal/index/index/', 'page=' . $page . "&channel=" . $channel );
	}
	
	public function getTpl() {
		$parseTag = service ( 'ParseTag' );
		$tpl = $_REQUEST ['tpl'];
		$sign = $_REQUEST ['sign'];
		$tagName = $_REQUEST ['tagName'];
		echo $parseTag->getTplContent ( $tpl, $tagName, $sign );
	}
	
	public function checkUserRole() {
		$page = t ( $_POST ['page'] );
		$page = empty ( $page ) ? "index" : $page;
		$channel = t ( $_POST ['channel'] );
		
		$databaseData = D ( 'Page' )->getPageInfo ( $page, $channel );
		$reuslt = $this->checkRole ( $databaseData ['manager'], $databaseData );
		D ( 'Page' )->addReader ( $databaseData ['dataId'] );
		//dump(intval($reuslt['admin']) );
		echo intval ( $reuslt ['admin'] );
		exit ();
	}
	
	private function checkRole($user, $pageInfo) {
		$admin = false;
		$openDiy = false;
		$userModel = model ( 'UserGroup' );
		if (in_array ( $this->mid, $user ) || $userModel->isAdmin ( $this->mid )) {
			$admin = true;
		}
		if (isset ( $_GET ['diy'] ) && $pageInfo ['pageType'] != 'list') {
			$openDiy = true;
		}
		
		$this->assign ( 'openDiy', $openDiy );
		$this->assign ( 'admin', $admin );
		$result ['admin'] = $admin;
		$result ['openDiy'] = $openDiy;
		return $result;
	}
	private function getLayout($layout, $page, $toChange) {
		$newLayout = json_decode ( $layout );
		$content = '';
		$count = 0;
		$preg = "/([\n\r\t\s]*)<DIV class=[\"']?bg_diy_tit(.*)[\"']?(.*)>(.*)<\/DIV>([\n\r\t\s]*)/siU";
		//dump($newLayout);
		foreach ( $newLayout as $key => $value ) {
			$count ++;
			$key = explode ( 'F', $key );
			$newId = $key [0] . 'F' . (time () + $count);
			$layoutL = "diy_" . $key [0] . "_L";
			$layoutR = "diy_" . $key [0] . "_R";
			$layoutC = "diy_" . $key [0] . "_C";
			$layoutP = "diy_" . $key [0] . "_P";
			
			$value->html = str_replace ( ' line_E', '', $value->html );
			$value->html = preg_replace ( $preg, '', $value->html );
			
			$html = $this->replaceHtml ( $layoutL, $value->html, $value->$layoutL, $newId );
			$html = $this->replaceHtml ( $layoutR, $html, $value->$layoutR, $newId );
			$html = $this->replaceHtml ( $layoutC, $html, $value->$layoutC, $newId );
			$html = $this->replaceHtml ( $layoutP, $html, $value->$layoutP, $newId );
			
			$content .= "<div id='" . $newId . "' class='diy_" . $key [0] . "'>";
			$content .= $html;
			$content .= "</div>";
		}
		return $content;
	}
	
	private function replaceHtml($layout, $htmlData, $data, $id) {
		if (isset ( $data )) {
			$parseTag = service ( 'ParseTag' );
			$widget = '';
			foreach ( $data as $key => $value ) {
				$tagInfo = $parseTag->getTagInfo ( $value );
				if ($tagInof ['tagName'] == 'w:custom') {
					$temp = sprintf ( '<div id="%s" rel = "%s" class="mb10 alL" sign= "%s">', $id . "-" . $layout . "-" . ($key + 1), $tagInfo ['tagName'], $value );
				} else {
					$temp = sprintf ( '<div id="%s" rel = "%s" class="mb10" sign= "%s">', $id . "-" . $layout . "-" . ($key + 1), $tagInfo ['tagName'], $value );
				}
				$temp .= "[widget:" . $value . "]";
				$temp .= "</div>";
				$this->layout [$id] [$layout] [$key] = $value;
				$widget .= $temp;
			}
			$r = sprintf ( '<div class="%s">%s</div>', $layout, $widget );
			$preg = "/([\n\r\t\s]*)<div class=[\"']" . $layout . "(.*)[\"'](.*)>(.*)<\/div>([\n\r\t\s]*)/siU";
			//$htmlData = preg_replace($preg2,'',$htmlData);
			

			$html = preg_replace ( $preg, $r, $htmlData );
			return $html;
		}
		return $htmlData;
	}
	
	private function _getTagWidget($post) {
		$tagName = $post ['tagName'];
		unset ( $post ['tagName'] );
		switch ($tagName) {
			case "w:image" :
				if (! empty ( $post ['image'] )) {
					$attr [] = "image_list=" . "\"" . htmlspecialchars ( json_encode ( $post ['image'] ) ) . "\"";
				}
				foreach ( $post as $key => $value ) {
					if (strpos ( $key, 'PARAM_' ) !== false && ! empty ( $value )) {
						$key = str_replace ( 'PARAM_', '', $key );
						$attr [] = $key . "=\"" . $value . "\"";
					}
				}
				$attr = implode ( ' ', $attr );
				break;
			case "w:custom" :
				$html = $post ['PARAM_html'];
				unset ( $post ['PARAM_html'] );
				foreach ( $post as $key => $value ) {
					if (strpos ( $key, 'PARAM_' ) !== false) {
						$key = str_replace ( 'PARAM_', '', $key );
						$attr [] = $key . "=\"" . $value . "\"";
					}
				}
				$attr = implode ( ' ', $attr );
				$result [0] = sprintf ( '<%s %s>%s</%s>', $tagName, $attr, $html, $tagName );
				$result [1] = sprintf ( '<%s %s/>', $tagName, $attr );
				return $result;
				break;
			case "w:tab" :
				
				if (! empty ( $post ['content'] )) {
					$attr [] = "content=" . "\"" . htmlspecialchars ( json_encode ( $post ['content'] ) ) . "\"";
				}
				
				foreach ( $post as $key => $value ) {
					if (strpos ( $key, 'PARAM_' ) !== false && ! empty ( $value )) {
						$key = str_replace ( 'PARAM_', '', $key );
						$attr [] = $key . "=\"" . $value . "\"";
					}
				}
				
				$attr = implode ( ' ', $attr );
				break;
			case "w:vote" :
				$voteDao = model ( 'Vote' );
				$add = $voteDao->addVote ( $_POST, $this->mid );
				$attr = 'id="' . $add . '" style="vote"';
				break;
			default :
				if (isset ( $post ['PARAM_order'] )) {
					$post ['PARAM_order'] = $post ['PARAM_order'] . " " . $post ['PARAM_order_t'];
				}
				unset ( $post ['PARAM_order_t'] );
				if (isset ( $post ['attach'] )) {
					$image = array_shift ( $post ['attach'] );
					list ( $id, $imageName ) = explode ( '|', $image );
					$map ['id'] = $id;
					$model = model ( 'Xattach' )->where ( $map )->field ( 'savepath,savename' )->find ();
					$post ['PARAM_image'] = SITE_URL . "/data/uploads/" . $model ['savepath'] . $model ['savename'];
				}
				
				$param = $post;
				foreach ( $param as $key => $value ) {
					if (strpos ( $key, 'PARAM_' ) !== false && ! empty ( $value )) {
						$key = str_replace ( 'PARAM_', '', $key );
						$attr [] = $key . "=\"" . $value . "\"";
					}
				}
				if (isset ( $post ['tag'] ) && ! empty ( $post ['tag'] )) {
					$attr [] = model ( 'Xtag' )->getTagId ( $post ['tag'] );
				}
				
				if (isset ( $post ['head_link'] ) && ! empty ( $post ['head_link'] )) {
					$post ['head_link'] = str_replace ( '[@]', '&', $post ['head_link'] );
					$attr [] = "head_link=" . "\"" . htmlspecialchars ( json_encode ( $post ['head_link'] ) ) . "\"";
				}
				
				$attr = implode ( ' ', $attr );
		}
		return sprintf ( '<%s %s/>', $tagName, $attr );
	}
	
	/**
	 * 获取分类树
	 */
	public function getTree() {
		$category_list = M ( 'WikiCategory' )->findAll ();
		return $this->_formatTree ( $category_list );
	}
	
	public function getBlogCate() {
		echo json_encode($this->getBlogCateList ( $_POST ['gid'] ));
	}
	
	public function getWikiCate() {
		echo $this->getWikiCateList ( $_POST ['gid'] );
	}
	public function getFileCate() {
		echo $this->getFileCateList ( $_POST ['gid'] );
	}
	public function getForumCate() {
		echo $this->getForumCateList ( $_POST ['gid'] );
	}
	
	private function getWikiCateList($gid) {
		$gid = intval ( $gid );
		if ($gid != 0) {
			$service = service ( 'Category' );
			$service->setParam ( 'ts_group_wiki_category', $gid );
			return json_encode ( $service->_format ( $service->getCategoryList () ) );
		} else {
			return false;
		}
	}
	
	private function getFileCateList($gid) {
		$gid = intval ( $gid );
		if ($gid != 0) {
			$service = service ( 'Category' );
			$service->setParam ( 'ts_group_file_cate', $gid );
			return json_encode ( $service->_format ( $service->getCategoryList () ) );
		} else {
			return false;
		}
	}
	
	private function getBlogCateList($gid) {
		$gid = intval ( $gid );
		if ($gid != 0) {
			$model = D ( 'BlogCategory', "blog" );
			$data = $model->getUserCategory ( $gid, 'group' );
			$pid = getSubByKey ( $data, "pid" );
			$tempGid = getSubByKey ( $data, "uid" );
			
			$map ['id'] = array ('in', $pid );
			$temp = $model->where ( $map )->field ( 'id,name' )->findAll ();
			
			$temp = group ( $temp, 'id' );
			
			foreach ( $data as $key => $value ) {
				$data [$key] ['parent'] = $temp [$value ['pid']] [0] ['name'];
			}
			return  group ( $data, "parent" ) ;
		} else {
			return false;
		}
	}
	
	private function getForumCateList($gid) {
		$gid = intval ( $gid );
		if ($gid != 0) {
			$categoryMap ['gid'] = array ('in', $gid );
			$data = M ( 'group_forum_category' )->where ( $categoryMap )->order ( 'ordernum ASC' )->findall ();
			$groupId = getSubByKey ( $data, 'gid' );
			$map ['gid'] = array ('in', $groupId );
			$group = D ( 'Group_x' )->where ( $map )->field ( 'gid,name' )->findAll ();
			$temp = group ( $group, 'gid' );
			foreach ( $data as $key => $value ) {
				$data [$key] ['group'] = $temp [$value ['gid']] [0] ['name'];
			}
			return  group ( $data, "group" ) ;
		} else {
			return false;
		}
	}
	
	//格式化分类树
	protected function _formatTree($category_list, $parent_id = NULL, $level = 1, $max_level = 3) {
		$result = array ();
		$index = 0;
		foreach ( $category_list as $k => $v ) {
			$flag = isset ( $parent_id ) ? (($v ['level'] == $level) && ($this->_isParentCategory ( $parent_id, $v ))) : ($v ['level'] == $level);
			if ($flag) {
				$result [$index] ['a'] = $v ['id'];
				$result [$index] ['t'] = $v ['name'];
				$result [$index] ['order'] = $v ['displayOrder'];
				if ($level < $max_level) {
					$result [$index] ['d'] = $this->_formatTree ( $category_list, $v ['id'], $level + 1, $max_level );
				}
				$index ++;
			}
		}
		return $result;
	}
	
	public function getMyGroup() {
		$limit = intval ( $_POST ['limit'] );
		$order = $_POST ['order'];
		$res = $this->_usingUser ( $this->mid, $limit, $order );
		$data ['list'] = $res;
		$data ['title'] = empty ( $_POST ['title'] ) ? "我的团队" : $_POST ['title'];
		$data ['dis_count'] = empty ( $_POST ['count'] ) ? 1 : intval ( $_POST ['count'] );
		$this->assign ( $data );
		$this->display ();
	}
	
	private function _getSqlByUser($order, $method, $limit, $uid) {
		$where = $where2 = '';
		
		if ($order == 'counts') {
			$order = 'ORDER BY count ' . $method;
		} else {
			$order = 'ORDER BY xgroup.' . $order . ' ' . $method;
		}
		if (! empty ( $uid )) {
			if (strstr ( $uid, ',' )) {
				$where = 'AND uid IN ( ' . implode ( ',', $uid ) . ' ) ';
			} else {
				$where = 'AND uid = ' . $uid;
			}
		}
		
		if ($uid == $this->mid) {
			$getUserGidSql = 'select gid from`ts_group_x_member` where status = 1 ' . $where;
		} else {
			$getUserGidSql = 'select gid from`ts_group_x` where status = 1 AND browser = 0 ' . $where;
		}
		$gid = $this->_format ( M ( '' )->query ( $getUserGidSql ), 'gid' );
		if ($gid && ! empty ( $gid )) {
			$where2 = implode ( ',', $gid );
		}
		$sql = 'select count(mgroup.uid) as count,xgroup.gid,xgroup.uid,xgroup.name,xgroup.description,xgroup.category,xgroup.icon,xgroup.visitcount,xgroup.cTime
				from `ts_group_x_member` as mgroup,`ts_group_x` as xgroup
				where mgroup.gid IN (' . $where2 . ') AND xgroup.gid = mgroup.gid
				GROUP BY xgroup.gid
				' . $order . ' 
				LIMIT 0,' . $limit;
		return $sql;
	}
	//获取给定用户ID的所有群组，以"level DESC"排序
	protected function _usingUser($uid, $limit = 20, $order = 'level DESC') {
		$res = array ();
		//获取给定用户参加的团队IDs [已通过审核 & 非私密团队]
		$res = array ();
		list ( $orderMethod, $order ) = explode ( ' ', $order );
		switch ($orderMethod) {
			case "users" :
				$sql = $this->_getSqlByUser ( 'counts', $order, $limit, $uid );
				break;
			default :
				$sql = $this->_getSqlByUser ( $orderMethod, $order, $limit, $uid );
		}
		
		$res = M ( '' )->query ( $sql );
		return $res;
	}
	
	/**
	 * 判读[param1]是否为[param2]的父分类
	 *
	 * @parent  int
	 * @son     array
	 * @return  boolean
	 */
	protected function _isParentCategory($parent, $son) {
		$son_navigation = unserialize ( $son ['navigation'] );
		foreach ( $son_navigation as $v ) {
			if ($v ['cid'] == $parent && $v ['cid'] != $son ['id']) {
				return true;
			}
		}
		return false;
	}
	
	//将二维数组格式化为一维数组
	protected function _format($arr, $field) {
		$res = array ();
		foreach ( $arr as $v ) {
			$res [] = $v [$field];
		}
		return $res;
	}
}

//模板用的自定义函数
if (! function_exists ( 'getGroupIcon' )) {
	function getGroupIcon($url) {
		$file = SITE_URL . '/data/uploads/' . $url;
		if (! empty ( $url ) && file_exists ( SITE_PATH . '/data/uploads/' . $url )) {
			return $file;
		} else {
			return SITE_URL . '/public/images/groupShadow.gif';
		}
	}
}